package com.woniu.controller;

import com.woniu.commom.CommonResult;
import com.woniu.commom.QiniuUploadUtil;
import com.woniu.commom.SensitivewordFilter;
import com.woniu.dto.DynamicCommentDTO;
import com.woniu.dto.DynamicDTO;
import com.woniu.pojo.Dynamic;
import com.woniu.pojo.DynamicTags;
import com.woniu.pojo.Friends;
import com.woniu.service.DynamicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@RequestMapping("/dynamic")
@Controller
@CrossOrigin

public class DynamicController {
 @Autowired
 private DynamicService dynamicService;


    /**
     * 展示社区动态
     * @param currentPage
     * @param pageSize
     * @return
     */
 @RequestMapping("/list")
 @ResponseBody
 public Map list(@RequestParam(value = "page", defaultValue = "1", required = false) Integer currentPage,
                          @RequestParam(value = "limit", defaultValue = "100", required = false) Integer pageSize) {

             List<DynamicDTO> dynamics=dynamicService.selectDTOByPage(currentPage,pageSize);
             Map map = new HashMap();
             map.put("dynamics",dynamics);
             return map;
 }



    /**
     * 好友动态展示
     * @param userId
     * @return
     */
    @RequestMapping("/friendDynamicList/{userId}")
     @ResponseBody
 public Map friendDynamicList(@PathVariable("userId") Long userId){
    Map map = new HashMap();
    List<Long> friendsId=dynamicService.selectFriendsId(userId);
//    if(friendsId==null  || friendsId.size()<1){
//        map.put("code",201);
//        return map;
//    }
        List<DynamicDTO> friendsDynamic=dynamicService.selectFriendBynamic(friendsId);
        map.put("code",200);
        map.put("friendsDynamic",friendsDynamic);
        return map;
 }

    /**
     * 更改动态时动态的数据
     * @param dynamicId
     * @return
     */
    @RequestMapping("/selectDynamic/{dynamicId}")
@ResponseBody
 public Dynamic selectDynamic(@PathVariable("dynamicId") Long dynamicId){
      return   dynamicService.selectDynamic(dynamicId);
 }




    /**
     * 文件上传
     * @param file 上传的文件
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public CommonResult upload(@RequestParam("file")MultipartFile file) {
        //获取文件名(自己编写)
        String fileName = UUID.randomUUID().toString();
        try {
            //返回的路径，即可存入数据库，即可以在网上直接访问（new       QiniuUploadUtil().upload）调取Util里面方法；
            //QiniuUploadUtil工具类不需要做任何修改
            String imgurl = new QiniuUploadUtil().upload(fileName, file.getBytes());
           // System.out.println(imgurl);
            Map map=new HashMap();
            map.put("src",imgurl);
            return CommonResult.success("上传成功",map);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.success("上传失败");
        }
    }



 /**
  * 发布动态
  *
  * @return
  */
 @RequestMapping("/release")
 @ResponseBody
 public CommonResult releaseDynamic( @RequestParam("uid") Long uid,Dynamic dynamic,@RequestParam("imgs") String imgs ) {
     System.out.println("用户id"+uid);
     System.out.println("文本值"+dynamic.getContent());
     System.out.println("图片地址"+imgs);


     SensitivewordFilter filter = new SensitivewordFilter();

      String string=dynamic.getContent();

     long beginTime = System.currentTimeMillis();
     //判断是否包含敏感词
     boolean b= filter.isContaintSensitiveWord(string,2);
     //取出敏感词
     Set<String> set = filter.getSensitiveWord(string, 2);
     long endTime = System.currentTimeMillis();
     System.out.println("是否有敏感词"+b);
     System.out.println("待检测语句：" + string);
     System.out.println("待检测语句字数：" + string.length());
     System.out.println("敏感词的数量：" + filter.sensitiveWordMap.size());
     System.out.println("语句中包含敏感词的个数为：" + set.size() + "。包含：" + set);
     System.out.println("总共消耗时间为：" + (endTime - beginTime));

   if(b){
    return CommonResult.failed("发布失败！内容包含敏感词汇。");
   }


//发布时间
   dynamic.setCreateTime(new Date());

  try {

   dynamicService.release(dynamic,uid,imgs);
   return CommonResult.success();
  } catch (Exception e) {
   e.printStackTrace();
   return CommonResult.failed("发布动态失败");
  }

 }

 /**
  * 更新动态
  *
  * @return
  */
 @RequestMapping("/update")
 @ResponseBody
 public Map updateDynamic(String content,Long id,String imgs) {
     //System.out.println("更改:"+id);
     Map map=new HashMap();
     Dynamic dynamic = dynamicService.selectDynamic(id);
    // System.out.println("更改uid:"+dynamic.getUserId());
     if(content!="" &&content!=null){
         dynamic.setContent(content);
     }
     dynamic.setUpdateTime(new Date());

     try {
         dynamicService.updateDynamic(dynamic,imgs);
         map.put("code",200);
         return map;
     } catch (Exception e) {
         e.printStackTrace();
         map.put("code",500);
         return map;
     }
 }

    /**
     * 删除动态
     * @param dynamicId
     * @return
     */
 @ResponseBody
 @RequestMapping("/deleteDynamic/{dynamicId}")
 public Map deleteDynamic(@PathVariable("dynamicId") Long dynamicId){
     Map map=new HashMap();
     try {
         dynamicService.deleteDynamic(dynamicId);
         map.put("code",200);
         return map;
     } catch (Exception e) {
         e.printStackTrace();
         map.put("code",500);
         return map;
     }
 }






    /**
     * 动态详情
     * @param id
     * @return
     */
 @RequestMapping("/showDynamic/{dynamicId}/{userId}")
 @ResponseBody
 public  Map showDynamicDetail(@PathVariable("dynamicId") Long id,@PathVariable("userId") Long userId){
    // System.out.println("动态id"+id);
     Map map=new HashMap();
     DynamicDTO detail=dynamicService.selectDynamicById(id);
     //查询点赞的人
     List<String> persons=dynamicService.selectPersonsByDynamicId(id);
    //查询点赞动态的人数
     Integer personNum=dynamicService.selectPersonNum(id);
     //查询评论
     List<DynamicCommentDTO> comments=dynamicService.selectComments(id);
    //根据id查询点赞信息，进行点赞图标相应显示，有这个人的信息则图标变红
     List<DynamicTags> tags=dynamicService.selectTags(id);
    //增加动态浏览数
     dynamicService.addLikeNum(id);
     //判断是否已关注该还有，如果已关注，则详情页面显示已关注
     Long dynamicUserId=dynamicService.selectUserId(id);
     Friends friends=dynamicService.selectFriend(dynamicUserId,userId);
     if(friends!=null){
         map.put("code",200);
     }else{
         map.put("code",500);
     }

      map.put("detail",detail);
      map.put("persons",persons);
      map.put("personNum",personNum);
      map.put("comments",comments);
      map.put("tags",tags);
      return  map;
 }

    /**
     * 增加点赞
     * @param dynamicId
     * @param userId
     */
    @ResponseBody
@RequestMapping("/addTag/{dynamicId}/{userId}")
 public  Map addTag(@PathVariable("dynamicId") Long dynamicId,@PathVariable("userId")Long userId){
        Map map=new HashMap();
        try {
            dynamicService.addTag(dynamicId,userId);

            map.put("code",200);
            return  map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",500);
            return  map;
        }
//        List<String> persons=dynamicService.selectPersonsByDynamicId(dynamicId);
//        Integer personNum=dynamicService.selectPersonNum(dynamicId);

 }

    /**
     * 取消点赞
     * @param dynamicId
     * @param userId
     */
    @ResponseBody
    @RequestMapping("/reduceTag/{dynamicId}/{userId}")
    public  Map reduceTag(@PathVariable("dynamicId") Long dynamicId,@PathVariable("userId")Long userId){
        Map map=new HashMap();
        try {
            dynamicService.reduceTag(dynamicId,userId);
            map.put("code",200);
            return  map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",500);
            return  map;
        }
//        List<String> persons=dynamicService.selectPersonsByDynamicId(dynamicId);
//        Integer personNum=dynamicService.selectPersonNum(dynamicId);


//        map.put("persons",persons);
//        map.put("personNum",personNum);


    }

    /**
     * 发布评论
     * @param dynamicId
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping("/addComment/{dynamicId}/{userId}")
    public  Map addComment(String comment,@PathVariable("dynamicId") Long dynamicId,@PathVariable("userId")Long userId){
        Map map=new HashMap();
        try {
            dynamicService.addComment(comment,dynamicId,userId);
            map.put("code",200);
            return  map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",500);
            return  map;
        }
//        List<DynamicCommentDTO> comments=dynamicService.selectComments(dynamicId);
//        map.put("persons",comments);


    }

    /**
     * 删除评论
     * @param dynamic
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteComment/{id}/{dynamic}")
    public  Map deleteComment(@PathVariable("id") Long id,@PathVariable("dynamic") Long dynamic){
        Map map=new HashMap();
        try {
            dynamicService.deleteComment(id,dynamic);
            map.put("code",200);
            return  map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",500);
            return  map;
        }
//        List<DynamicCommentDTO> comments=dynamicService.selectComments(dynamicId);
//        Map map=new HashMap();
//
//        map.put("persons",comments);
//
//
//        return  map;
    }


    /**
     * 关注好友
     * @param friendId
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping("/addFriend/{friendId}/{userId}")
    public  Map addFriend(@PathVariable("friendId") Long friendId,@PathVariable("userId") Long userId){
        Map map=new HashMap();
        try {
            dynamicService.addFriend(friendId,userId);
            map.put("code",200);
            return  map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",500);
            return  map;
        }

    }


    /**
     * 取消关注好友
     * @param friendId
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping("/reduceFriend/{friendId}/{userId}")
    public  Map reduceFriend(@PathVariable("friendId") Long friendId,@PathVariable("userId") Long userId){
        Map map=new HashMap();
        try {
            dynamicService.reduceFriend(friendId,userId);
            map.put("code",200);
            return  map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",500);
            return  map;
        }

    }





}